package com.zsy.websocket;

import cn.hutool.json.JSONObject;
import com.zsy.Ai.TongYiA;
import com.zsy.entity.WebSocketUser;
import com.zsy.mapper.IContractMapper;
//import com.zsy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.*;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@ServerEndpoint("/websocket/{username}")
@Component
public class MyWebSocketServer {


    private static Map<String, Session> sessions = new ConcurrentHashMap<>();
    private static AtomicInteger onlineNum = new AtomicInteger(0);

    // 打开连接
    @OnOpen
    public void onOpen(Session session,@PathParam(value = "username") String username) {
        try {
            onlineNum.incrementAndGet();
            System.out.println("连接打开"+session.getId());
            System.out.println("当前在线人数"+onlineNum.get());
            sessions.put(username,session);
            System.out.println(sessions.get(username));
            String message = "用户："+username+"已上线";
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(sessions.get(username));

    }


    //    单对单
    @OnMessage
    public void onMessage(String message) throws IOException {

        JSONObject jsonMessage = new JSONObject(message);
        String username = jsonMessage.getStr("username");
        String content = jsonMessage.getStr("message");
        //拿到目标用户的用户名与session
//        String username = message.getUsername();
//        Session session = sessions.get(username);
        Session session = sessions.get(username);
        //ai生成消息
        String s = TongYiA.TongYi(content);
        session.getBasicRemote().sendText(s);

//        try {
//            //发送对象
//            session.getBasicRemote().sendObject(message);
//        } catch (EncodeException e) {
//            throw new RuntimeException(e);
//        }
//        System.out.println("用户"+username+"消息："+message.getContent());
    }
    public void sendMessage(String message){
        try {
            onMessage(message);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnClose
    public void onClose(@PathParam("username") String username) {
        System.out.println(username);
        // 移除会话
        sessions.remove(username);
        System.out.println("用户："+username+"已下线");
        onlineNum.decrementAndGet();
        System.out.println("当前在线人数"+onlineNum.get());
    }

    @OnError
    public void onError(Throwable throwable) {
        System.out.println("报错");
        System.err.println("Error occurred: " + throwable.getMessage());
    }

    //判断用户是否在线 containsKey查看ConcurrentHashMap中是否有指定的键，有就返回true，isOpen检查会话是否处于打开状态，打开返回true
    public  boolean isUserOnline(String username){
        return sessions.containsKey(username) && sessions.get(username).isOpen();
    }
}